import React from 'react';
import { Upload, Button, Icon, Form, message } from 'antd';
import { connect } from 'react-redux'
import { API_URL,PORTRAIT } from '../../store/actions';

const FormItem = Form.Item;

class _Avatar extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props.user,
            fileList:{}
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.normFile = this.normFile.bind(this)
    }

    normFile(e) {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    handleSubmit(e){
        e.preventDefault();
    }
    handleChange(info){
        let fileList = info.fileList;

        // 1. 上传列表数量的限制
        //    只显示最近上传的一个，旧的会被新的顶掉
        fileList = fileList.slice(-2);


        if (info.file.status !== 'uploading') {}
        if (info.file.status === 'done') {
            message.success(`${info.file.name} 上传成功。`);

        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败。`);
        }
    }
    render(){
        const { getFieldProps } = this.props.form;


        const upload1 = getFieldProps('upload', {
            valuePropName: 'portrait',
            normalize: this.normFile,
            onChange: this.handleChange,
            rules: [
                { required: true,
                    message: '必须上传有效影片' }
            ]
        });
        return (
            <div>

                <Form horizontal onSubmit={this.handleSubmit}>
                    <FormItem
                        label="上传头像"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        help="请上传头像图片"
                    >
                        <Upload
                            name="portrait"
                            showUploadList={false}
                            action= {`${API_URL}${PORTRAIT}?accessToken=${this.props.user.accessToken}`}
                            {...upload1}
                        >
                            <Button type="ghost">
                                <Icon type="upload" /> 选择并上传头像
                            </Button>
                        </Upload>

                    </FormItem>

                </Form>

            </div>)
    }
}
_Avatar = Form.create()(_Avatar);
let Avatar;
export default Avatar = connect((state) => {
    const {user} = state.rootReducer;
    return {user}
})(_Avatar)